package controllers;

import is.ru.honn.rupin.data.PinDataGateway;
import is.ru.honn.rupin.domain.Board;
import is.ru.honn.rupin.domain.Pin;
import is.ru.honn.rupin.service.PinService;
import is.ru.honn.rupin.service.UserNotFoundException;
import is.ru.honn.rupin.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.boards.*;

import java.util.List;

/**
 * Controller for board actions
 * @author Einar Sigurðsson
 * @version 1.0, 11/19/12
 */
public class BoardController extends RuPinController {
    final static Form<Board> signupForm = form(Board.class);

    /**
     * Returns the board which corresponds the username and boardname
     * @param username the username
     * @param boardname the name of the board
     * @return summary of all the pins on the board
     */
    public static Result getBoard(String username, String boardname){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        List<Pin> pins = pinService.getPinsOnBoard(username, boardname);
        if(!session().get("username").equals(username))
            return ok(board.render(pins, boardname, userService.getUser(username), false));
        else
            return ok(board.render(pins, boardname, userService.getUser(username), true));
    }

    /**
     * Returns an empty form for board
     * @return the view for board/form.scala
     */
    public static Result addForm(){
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        return ok(form.render(signupForm));
    }

    /**
     * Adds a board to the database
     * @return the view of the newly created board
     */
    public static Result add()
    {
        if(!Session.isValidated())
            return redirect(routes.Session.login());
        Form<Board> filledForm = signupForm.bindFromRequest();

        if (filledForm.hasErrors()){
            return badRequest(form.render(filledForm));
        }else{
            Board created = filledForm.get();
            System.out.println("created board: " + created);
            try{
            pinService.createBoard(session().get("username"), filledForm.get().getName(), filledForm.get().getCategory());
            }
            catch(UserNotFoundException e){
                return badRequest();
            }
            return redirect(routes.BoardController.getBoard(session().get("username"), created.getName()));
        }
    }
}
